<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <span>111111</span>
    <div class="box">
      <span class="box-first">呵呵呵呵</span>
      <p>哈哈哈哈哈</p>
    </div>

    <button class="remove-btn">移除box</button>
    <button class="clone-btn">复制box</button>

    <div class="box">
      <h2>标题</h2>
      <p>文本内容</p>
    </div>

    <script>
      var boxEl = document.querySelector(".box");

      // 1.通过innerHTML(一般用于插入普通文本)
      // boxEl.innerHTML = `
      //   <h2 class="title">我是标题</h2>
      // `

      // 2.真实创建一个DOM对象
      var h2El = document.createElement("h2");
      h2El.className = "title";
      h2El.classList.add("active");
      h2El.textContent = "我是标题";

      // 将元素插入boxEl
      // boxEl.append(h2El) // 在boxEl中追加一个元素，子元素的最后一个
      // boxEl.prepend(h2El) //子元素的第一个
      // boxEl.after(h2El)
      // boxEl.before(h2El)
      // boxEl.replaceWith(h2El, "abc")

      // 插入到span和p元素之间
      // var spanEl = document.querySelector("span")
      // var spanEl = boxEl.children[0]
      var spanEl = boxEl.querySelector("span"); //元素可以调用querySelector

      spanEl.after(h2El);

      // 1.获取元素
      var boxEl = document.querySelector(".box");
      var removeBtnEl = document.querySelector(".remove-btn");
      var cloneBtnEl = document.querySelector(".clone-btn");

      // 2.监听removeBtn的点击
      removeBtnEl.onclick = function () {
        boxEl.remove(); //子元素也会被移除
      };

      // 3.复制box
      var counter = 0;
      cloneBtnEl.onclick = function () {
        var newNode = boxEl.cloneNode(true); //参数：是否deepClone
        newNode.children[0].textContent = "我是标题" + counter;
        // boxEl.after(newNode)
        document.body.append(newNode);

        counter++;
      };
    </script>
  </body>
</html>
